package binary_search;

/**
 * 704. 二分查找
 * 切记区分[left,right]和[left, right)
 * [left,right]左闭右闭区间时，while中的条件为left<=right
 * [left,right)左闭右开区间时，while中的条件为left<right
 *
 * @author Api
 * @date 2023/10/6 13:51
 */
public class Code704_BinarySearch {
    // 二分查找[left,right]区间写法
    public int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = (left + right) >> 1;
            if (nums[mid] > target) {
                right = mid - 1;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else {
                return mid;
            }
        }
        return -1;
    }

    // 二分查找[left,right)区间写法
    public int search1(int[] nums, int target) {
        int left = 0;
        int right = nums.length;
        while (left < right) {
            int mid = (left + right) >> 1;
            if (nums[mid] > target) {
                right = mid;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else {
                return mid;
            }
        }
        return -1;
    }
}
